/****** 所有的自定义埋点事件 ******/
let zldata = {},
  zla = {}
if (typeof window !== 'undefined') {
  //初始化神策
  var host = location.host
  var serverUrl = 'https://shenji.zlketang.com:9443'
  var reg = /^(www\.|cp\.|wap\.|cpm\.)?zlketang/
  if (reg.test(host)) {
    //正式环境提交地址
    serverUrl = 'https://data.zlketang.com'
  }
  zldata = new ZlData({
    //之了数据接收上报域名
    serverUrl: serverUrl,
    //当前项目接口的访问域名
    baseUrl: '',
    //APP秘钥
    appSecret: '202005061001',
    //APP id
    appId: '202005060001'
  })
  //开启之了上传事件
  zldataAction()
  function zldataAction() {
    try {
      //下面是执行用户绑定的神策操作
      zldata
        .quick('isReady', function() {
          //创建公共属性
          zldata.registerPage({
            platform_type: 'pc_web',
            user_register_type: '官网'
          })
        })
        .catch(function() {})
    } catch (error) {}
  }
  const pageMap = {
    '/': {
      is_report: 1,
      name: '官网首页',
      id: 921001
    },
    '/search/': {
      is_report: 1,
      name: '搜索页',
      id: 921002
    },
    '/$profession/$type/': {
      is_report: 1,
      name: '资讯列表页',
      id: 921003
    },
    '/$profession/$type/$id.html': {
      is_report: 1,
      name: '资讯详情页',
      id: 921004
    },
    '/teachers/$profession/': {
      is_report: 1,
      name: '老师列表页',
      id: 921005
    },
    '/teacher/$id/': {
      is_report: 1,
      name: '老师详情页',
      id: 921006
    },
    '/$profession/': {
      is_report: 1,
      name: '专业首页',
      id: 921007
    },
    '/courses/$profession_id.html': {
      is_report: 1,
      name: '商品列表页',
      id: 921008
    },
    '/course_detail.html': {
      is_report: 1,
      name: '商品详情页',
      id: 921009
    },
    '/personal/index.html': {
      is_report: 1,
      name: '个人中心',
      id: 921011
    },
    '/exercises/$profession': {
      is_report: 1,
      name: '题库页',
      id: 921012
    },
    '/vcourse/liveList.html': {
      is_report: 1,
      name: '直播列表页',
      id: 921013
    },
    '/login.html': {
      is_report: 1,
      name: '登录页',
      id: 921014
    },
    '/$profession/guide/': {
      is_report: 1,
      name: '报考指南页',
      id: 921015
    },
    '/pay/index.html': {
      is_report: 1,
      name: '购物车结算页',
      id: 921016
    },
    '/newUserActivity.html': {
      is_report: 1,
      name: '领课落地页',
      id: 921019
    },
    '/vcourse/live.html': {
      is_report: 1,
      name: '直播间页',
      id: 921023
    },
    '/beginner/': {
      is_report: 1,
      name: '之了介绍',
      id: 921022
    },
    '/exam/': {
      is_report: 1,
      name: '做题页',
      id: 921024
    },
    '/vplay/play.html': {
      is_report: 1,
      name: '看课页',
      id: 921017
    },
    '/vplay/free_course_play.html': {
      is_report: 1,
      name: '免费看课页',
      id: 921017
    },
    '/shixun/index.html': {
      is_report: 1,
      name: '实训中心-首页',
      id: 921028
    },
    '/shixun/make_account.html': {
      is_report: 1,
      name: '实训中心-做账/税务',
      id: 921026
    },
    '/shixun/make_account_question_list.html': {
      is_report: 1,
      name: '做账题目列表',
      id: 921027
    },
    '/shixun/search_result.html': {
      is_report: 1,
      name: '搜索结果页面',
      id: 921024
    },
    '/ScLanding.html': {
      is_report: 1,
      name: '实操落地页',
      id: 921025
    },
    '/publicity_page.html': {
      is_report: 1,
      name: '注会师资宣发落地页需求',
      id: 921029
    },
    '/double_certificates.html': {
      is_report: 1,
      name: '一年双证落地页',
      id: 921030
    },
    '/double_certificates_2023.html': {
      is_report: 1,
      name: '一年双证落地页',
      id: 921030
    },
    '/mock_exam/index.html': {
      is_report: 1,
      name: '万人模考',
      id: 906003
    },
    '/exam/mock_exam_do.html': {
      is_report: 1,
      name: '做题页面',
      id: 906005
    },
    '/exam/mock_exam_index/history.html': {
      is_report: 1,
      name: '万人模考',
      id: 906004
    },
    '/mock_exam/cpa_exam.html': {
      is_report: 1,
      name: '万人模考',
      id: 906010
    },
    '/books/': {
      is_report: 1,
      name: '图书页',
      id: 921031
    },
    '/exam/sprint_activity/index.html': {
      is_report: 1,
      name: '冲刺活动首页',
      id: 906006
    },
    '/exam/sprint_activity/exam.html': {
      is_report: 1,
      name: '冲刺活动做题页',
      id: 906007
    },
    '/exam/cpa_exam.html': {
      is_report: 1,
      name: '注会做题页',
      id: 921035
    },
    '/exam/cpa_exam_question.html': {
      is_report: 1,
      name: '注会错题收藏',
      id: 921036 
    },
    '/study_center/index.html': {
      is_report: 1,
      name: '学习中心',
      id: 904004
    },
    '/dayi/': {
      is_report: 1,
      name: '答疑中心',
      id: 921032
    },
    '/ask/': {
      is_report: 1,
      name: '答疑提问页',
      id: 921034
    },
    '/fissionHome.html': {
      is_report: 1,
      name: '之了课堂福利站',
      id: 921039
    },
    '/groupDetail.html': {
      is_report: 1,
      name: '之了课堂福利站商品详情页',
      id: 921040
    },
    '/groupOrder.html': {
      is_report: 1,
      name: '之了课堂福利站助力页',
      id: 921041
    },
    '/study_center_entry.html': {
      is_report: 1,
      name: '学习中心入口',
      id: 922001
    },
    '/common_study_center/study_course.html': {
      is_report: 1,
      name: '学习中心课程页',
      id: 922002
    }    
   
  }
  // 加载js获取本地ip地址返回值：var returnCitySN = {"cip": "222.209.208.45", "cid": "510100", "cname": "四川省成都市"};
  let currentPage = {},
    subjectInfo = {}
  currentPage = comPageInfo(location.pathname)
  let subjectIndexCache = localStorage.getItem('subjectIndex')
  if (subjectIndexCache) {
    try {
      subjectInfo = JSON.parse(subjectIndexCache)
    } catch (e) {}
  }
  function comPageInfo(pathname) {
    // 资讯栏目
    const types = [
      'all',
      'dynamic',
      'policy',
      'infos',
      'learn',
      'experience',
      'stuff',
      'exam',
      'simulation',
      'chapter',
      'keynote',
      'month',
      'practice',
      'book',
      'course'
    ]
    // 省份简称
    const arreas = [
      'all',
      'bj',
      'fj',
      'gs',
      'gd',
      'gx',
      'gz',
      'hi',
      'he',
      'ha',
      'hl',
      'hb',
      'hn',
      'jl',
      'js',
      'jx',
      'ln',
      'im',
      'nx',
      'qh',
      'sd',
      'sx',
      'sn',
      'sh',
      'sc',
      'tj',
      'xz',
      'xj',
      'yn',
      'zj',
      'cq',
      'ah'
    ]
    const professions = ['all', 'cjkj', 'zjkj', 'cpa', 'cta', 'kjsc', 'mat_g', 'cma', 'zjjjs']
    // 确定的页面路径
    if (pageMap[pathname]) return pageMap[pathname]
    // 去掉以‘/’结尾
    let _pathname = pathname.replace(/\/$/, '')
    _pathname = _pathname.replace(/^\//, '')
    // 去掉以‘?’结尾
    let path_arr = _pathname.split('/')
    if (!Array.isArray(path_arr) || path_arr.length === 0) {
      return pageMap['/']
    }
    let firstPath = path_arr[0],
      secondPath = path_arr[1],
      thirdPath = path_arr[2]
    // 题库页
    if (firstPath === 'exercises') {
      return pageMap['/exercises/$profession']
    }
    // 专业首页
    if (professions.includes(firstPath) && !secondPath) {
      return pageMap['/$profession/']
    }
    // 资讯列表页
    if (professions.includes(firstPath) && (types.includes(secondPath) || arreas.includes(secondPath))) {
      return pageMap['/$profession/$type/']
    }
    // 资讯详情页
    if (professions.includes(firstPath) && secondPath.includes('_detail') && thirdPath.includes('.html')) {
      return pageMap['/$profession/$type/$id.html']
    }
    // 老师列表页
    if (firstPath === 'teachers' && professions.includes(secondPath)) {
      return pageMap['/teachers/$profession/']
    }
    // 老师详情页
    if (firstPath === 'teacher' && secondPath.includes('.html')) {
      return pageMap['/teacher/$id/']
    }
    // 商品列表页
    if (firstPath === 'courses' && (!secondPath || secondPath.includes('.html'))) {
      return pageMap['/courses/$profession_id.html']
    }
    // 报考指南页
    if (professions.includes(firstPath) && secondPath.includes('guide')) {
      return pageMap['/$profession/guide/']
    }
  }
  const pageZlData = {
    //全局点击事件
    all: [
      {
        el: 'button',
        event: 'keyClick'
      }
    ],
    //课程详情页所有的埋点
    videoCourse: [],
    //题库试题列表页
    questionPart: [
      {
        el: '.van-collapse-item',
        event: 'startAnswerQuestion'
      }
    ],

    //收藏错题本
    questionCollectError: [
      {
        el: '.van-collapse-item',
        event: 'startAnswerQuestion'
      }
    ]
  }

  zla = {
    //发送事件
    track(options) {
      try {
        if (!options) {
          return zldata
        }
        if (!options.event) return console.warn('未传入埋点事件！')
        zldata.track(options.event, options.properties, options.immediately).catch(e => {})
      } catch (e) {
        // console.error(JSON.stringify(e))
      }
    },
    //发送持续事件
    constTrack(options) {
      try {
        if (!options) {
          return zldata
        }
        if (!options.event) return console.warn('未传入埋点事件！')
        zldata.constTrack(options.event, options.properties, options.primaryKey).catch(e => {})
      } catch (e) {
        // console.error(JSON.stringify(e))
      }
    },

    /**
     * [checkSensorsElements 检测页面埋点元素是否存在]
     * @params {[Object]}  sensors [埋点信息]
     * @params {[String]}  sensors.sensorsElements [埋点元素信息]
     */
    checkZlDataElements(page) {
      if (!pageZlData[page]) return console.warn('该页面没有神策自定义埋点')

      let zlDataElements = pageZlData[page]

      //存储警告信息
      var warn = []

      //因为很多节点是动态生成的，所以直接调可能没有，加个定时器
      setTimeout(function() {
        zlDataElements.forEach(({ el, event }) => {
          var element = document.querySelector(el)
          //检测元素
          if (!element) {
            warn.push('页面缺少埋点元素： ' + el)
            return
          }
          //检测事件
          //事件不存在或当前或全局都没有这个事件，则报错
          if (!event) {
            warn.push(el + ' 元素缺少埋点事件： ' + (event ? event : ''))
          }
        })

        warn.forEach(item => console.warn(item))
      }, 1000)
    },
    //看课行为
    watchVideo(param) {
      let {
        course_id,
        class_id,
        teacher_id,
        video_id,
        progress,
        from_page_url,
        to_page_url,
        is_try,
        live_id,
        begin_time,
        catalog = '',
        product_id,
        profession_id,
        course_package_id = '',
        entry_time = ''
      } = param
      let pageInfo = comPageInfo(location.pathname)
      this.constTrack({
        event: 'watch_video',
        properties: {
          course_id,
          class_id,
          teacher_id,
          profession_id,
          product_id,
          video_id: video_id || 0,
          attach: {
            progress,
            source_page_id: pageInfo && pageInfo.id ? pageInfo.id : 0,
            to_page_url,
            live_id: live_id || 0,
            is_try: is_try || 0,
            page_id: currentPage.id || 0,
            catalog,
            begin_time,
            platform: 'pc_web',
            course_package_id,
            entry_time
          }
        },
        primaryKey: 'video_id'
      })
    },
    //浏览视频行为
    viewVideo(param, immediately = false) {
      let {
        course_id,
        class_id,
        teacher_id,
        video_id,
        from_page_url,
        live_id,
        is_try,
        catalog = '',
        to_page_url
      } = param
      let pageInfo = comPageInfo(location.pathname)

      //之前出现过上报video_id情况，造成后台上报报错。兼容video_id不存在的情况，保存事件
      if (typeof video_id !== 'number' || isNaN(video_id)) {
        video_id = 0
      }

      this.track({
        event: 'view_video',
        properties: {
          course_id,
          class_id,
          teacher_id,
          video_id,
          attach: {
            to_page_url,
            source_page_id: pageInfo && pageInfo.id ? pageInfo.id : 0,
            page_id: currentPage.id || 0,
            live_id: live_id || 0,
            is_try: is_try || 0,
            catalog,
            platform: 'pc_web'
          }
        },
        immediately
      })
    },

    //做题行为
    examPractice(param) {
      let { question_id, type, answer, user_answer, group_name, exam_id, exam_type } = param

      this.track({
        event: 'exam_practice',
        properties: {
          question_id,
          type,
          answer,
          user_answer,
          group_name,
          exam_id,
          exam_type,
          attach: {
            platform: 'pc_web'
          }
        }
      })
    },
    //考试行为
    examReal(param) {
      let { done_duration, progress, score, part_score, exam_id, exam_type } = param

      this.track({
        event: 'exam_real',
        properties: {
          done_duration,
          score,
          exam_id,
          exam_type,
          attach: {
            progress,
            part_score,
            platform: 'pc_web'
          }
        }
      })
    },
    // 周期性考试
    dateExam(param) {
      let { done_duration, progress, score, exam_key, part_score, subject_id, exam_type, date } = param
      let immediately = true

      this.track({
        event: 'date_exam',
        properties: {
          done_duration,
          score,
          exam_key,
          exam_type,
          date,
          attach: {
            progress,
            part_score,
            platform: 'pc_web'
          }
        },
        immediately
      })
    },
    //连续做题行为
    examProcess(param) {
      let { exam_key, progress, t, exam_type } = param
      this.constTrack({
        event: 'exam_process',
        properties: {
          exam_key,
          progress,
          t,
          exam_type,
          attach: {
            platform: 'pc_web'
          }
        },
        primaryKey: 'exam_key'
      })
    },
    //自定义按钮点击事件
    keyClick(params, immediately = false) {
      params.page_id = currentPage && currentPage.id ? currentPage.id : 0
      if (!params.attach) {
        params.attach = {
          platform: 'pc_web'
        }
      }
      params.attach.subject_id = params.attach.subject_id || +subjectInfo.subject_id || 0
      params.attach.profession_id = params.attach.profession_id || +subjectInfo.profession_id || 0

      try {
        const validate = {
          key_name: {
            type: 'string',
            length: [1, 100],
            keywords: /(location)|(script)|(window)/
          },
          key_content: {
            type: 'string',
            length: [1, 512],
            keywords: /(location)|(script)|(window)/
          }
        }

        let isError = Object.entries(validate).some(([key, value]) => {
          let str = params[key]
          let {
            type,
            length: [minLen = 0, maxLen = 100],
            keywords
          } = value
          //校验数据类型
          if (typeof str !== type) return true
          //校验数据长度
          if (str.length < minLen || str.length > maxLen) return true
          //校验关键词
          if (keywords.test(str)) return true
          return false
        })
        //校验不通过，不继续上报
        if (isError) return
        this.track({
          event: 'key_click',
          properties: params,
          immediately
        })
      } catch (e) {}
    },
    //自定义搜索事件
    zlaSearchWord(params) {
      this.track({
        event: 'search_word',
        properties: {
          ...params,
          // 用户ip
          ip: this.getCookie('user_address') ? this.getCookie('user_address') : '',
          // 搜索关键字
          // page_id/page_url/page_name
          page_url: location.href,
          page_id: currentPage && currentPage.id ? currentPage.id : 0,
          deviceid: localStorage.getItem('zldatasdk_deviceId') || ''
        },
        primaryKey: 'deviceid'
      })
    },
    getQuery(query) {
      var ret = {}
      var searchReg = /([^&=?]+)=([^&]+)/g
      var name, value
      let match = searchReg.exec(query)
      while (match) {
        name = match[1]
        value = match[2]
        ret[name] = decodeURIComponent(value)
        match = searchReg.exec(query)
      }
      return ret
    },

    // 浏览页面事件
    viewPage(immediately) {
      let _params = {}
      if (!currentPage || currentPage.is_report !== 1) return
      _params.page_id = currentPage.id
      _params.attach = {
        page_url: location.href,
        from_page_url: document.referrer,
        platform: 'pc_web'
      }
      try {
        this.track({
          event: 'view_page',
          properties: _params,
          immediately: immediately
        })
      } catch (e) {}
    },
    // 广告活动入口
    entryActivity(params) {
      // 广告位置
      const advertisementPostin = {
        1: {
          name: '新官网首页顶部广告位'
        },
        2: {
          name: '新官网首页顶部banner'
        },
        3: {
          name: '新官网首页公开课栏广告位'
        },
        4: {
          name: '新官网首页中部广告位'
        },
        5: {
          name: '新官网专业首页中部广告位'
        },
        6: {
          name: '新官网专业首页顶部banner'
        },
        7: {
          name: '新官网专业首页免费课二级广告位'
        },
        8: {
          name: '新官网专业首页之了名师二级广告位'
        },
        9: {
          name: '新官网专业首页直播公开课栏广告位'
        },
        10: {
          name: '新官网专业首页热门活动'
        },
        11: {
          name: '个人中心顶部广告位'
        },
        12: {
          name: '新官网题库首页顶部广告位'
        }
      }
      try {
        if (advertisementPostin[params.element_name]) {
          params.element_name = advertisementPostin[params.element_name].name
        }
        if (params.position_name) {
          params.element_name = params.position_name
          delete params.position_name
        }
        params.ads_name = params.ads_name && params.ads_name.length ? params.ads_name.substr(0, 30) : ''
        // params.attach = {
        //   platform: 'pc_web'
        // }
        params.attach = params.attach || {};
        params.attach.platform = 'pc_web';
        this.track({
          event: 'entry_activity',
          properties: params
        })
      } catch (e) {}
    },
    // 选择专业
    certificateSelected(params) {
      let { profession_id, subject_id } = params
      let _params = {
        profession_id,
        subject_id,
        page_id: currentPage.id || 0,
        attach: {
          platform: 'pc_web'
        }
      }
      try {
        this.track({
          event: 'certificate_selected',
          properties: _params
        })
      } catch (e) {}
    },
    // 持续观看直播
    watchLive(params) {
      try {
        if (!params.attach) {
          params.attach = {
            platform: 'pc_web'
          }
        } else {
          params.attach.platform = 'pc_web'
        }
        this.constTrack({
          event: 'watch_live',
          properties: params,
          primaryKey: 'live_id'
        })
      } catch (e) {}
    },
    // 用户坐标信息(立即上报)
    location(params = {}) {
      if (!Object.prototype.toString.call(params).includes('Object')) return
      if (!Object.keys(params).length) return

      try {
        this.track({
          event: 'location',
          properties: params,
          immediately: true
        })
      } catch (e) {}
    },
    //分专业页面浏览事件（切换专业时上报）
    professionPageView(params) {
      let { profession_id, subject_id, type } = params
      let attach = {
        platform: 'pc_web'
      }
      if (subject_id) attach.subject_id = subject_id
      if (type) attach.type = type
      this.track({
        event: 'profession_page_view',
        properties: {
          page_id: currentPage.id || 0,
          profession_id,
          attach: attach
        }
      })
    },
    // 浏览商品行为
    pageView(param) {
      if (!param.product_id) return
      let referrerId = ''
      if (document.referrer) {
        let pathname =
          '/' +
          document.referrer
            .split('/')
            .splice(3)
            .join('/')
        referrerId = comPageInfo(pathname) ? comPageInfo(pathname).id : ''
      }
      this.track({
        event: 'page_view',
        properties: {
          product_id: param.product_id,
          attach: {
            from_page_id: referrerId, //来源页页面id
            from_page_url: document.referrer || '',
            to_page_url: '',
            platform: 'pc_web'
          },
          title: document.title || '',
          is_purchased: param.is_purchased
        },
        immediately: true
      })
    }
  }
  try {
    zldata.quick &&
      zldata.quick('isReady', function() {
        zla.viewPage(true) // 立即上报事件
      })
  } catch (error) {}
}

export default { zla }
